<template>
    <el-dialog
    custom-class="ba-operate-dialog cu-dialog"
        :close-on-click-modal="false"
        :model-value="baTable.form.operate == 'detail' || baTable.form.operate == 'export'"
        @close="onClosed();"
        @open="onOpen"
        width="70%"
        destroy-on-close
        :fullscreen="true"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                项目详情 - {{ baTable.form.items!.title }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div class="container">
                <table class="content-table" border id="detail-table">
                    <tr>
                        <td colspan="3">PRODUCTION ESTIMATE</td>
                        <td colspan="8">{{ baTable.form.items!.custom_company }}</td>
                        <td rowspan="9" width="200">&nbsp;</td>
                    </tr>
                    <tr>
                        <td colspan="2">Client  客户：</td>
                        <td>{{ baTable.form.items!.custom_name }}</td>
                        <td colspan="4">片名：</td>
                        <td colspan="4">{{baTable.form.items!.title}}</td>
                    </tr>
                    <tr>
                        <td colspan="2">Creative Director 创意总监：</td>
                        <td>{{ baTable.form.items!.creative_director }}</td>
                        <td colspan="4">Language  语言:</td>
                        <td colspan="4">{{ baTable.form.items!.language }}</td>
                    </tr>
                    <tr>
                        <td colspan="2">Director  导演：</td>
                        <td>{{baTable.form.items!.director}}</td>
                        <td colspan="4">Prep Days  前期:</td>
                        <td colspan="4"></td>
                    </tr>
                    <tr>
                        <td colspan="2">DOP  摄影：</td>
                        <td></td>
                        <td colspan="4">Post Days  后期:</td>
                        <td colspan="4"></td>
                    </tr>
                    <tr>
                        <td colspan="2">Production Company 制作公司：</td>
                        <td></td>
                        <td colspan="4">Studio Shooting Day  棚内天数:</td>
                        <td colspan="4"></td>
                    </tr>
                    <tr>
                        <td colspan="2">Executive Producer  监制：</td>
                        <td></td>
                        <td colspan="4">Length  长度:</td>
                        <td colspan="4"></td>
                    </tr>
                    <tr>
                        <td colspan="2">Producer  制片：</td>
                        <td></td>
                        <td colspan="4">Date  制表日期 :</td>
                        <td colspan="4">{{ baTable.form.items!.date }}</td>
                    </tr>
                    <tr>
                        <td colspan="11"> &nbsp;&nbsp; </td>
                    </tr>
                    <tr class="bold">
                        <td colspan="7" width="80">Estimated Production Cost  制作成本</td>
                        <td>预算栏</td>
                        <td>核算栏</td>
                        <td>已支付</td>
                        <td>未支付</td>
                        <td></td>
                    </tr>
                    <tr :key="index" v-for="item, index in statics">
                        <td width="80">{{ letters[index] }}</td>
                        <td colspan="6" align="left">{{ item.title }}</td>
                        <td>{{item.budget}}</td>
                        <td>{{item.calculate}}</td>
                        <td>{{item.paid}}</td>
                        <td>{{item.no_paid}}</td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="12">&nbsp;&nbsp;</td>
                    </tr>
                    <tr>
                        <td colspan="7">Total 总签价</td>
                        <td :key="index" v-for="item, index in 5"></td>
                    </tr>
                    <tr>
                        <td colspan="2">Sub Total</td>
                        <td colspan="5">总价无税金</td>
                        <td>￥{{parseMOney(projectTotal.total.budget, true)}}</td>
                        <td>￥{{parseMOney(projectTotal.total.calculate, true)}}</td>
                        <td :key="index" v-for="item, index in 3"></td>
                    </tr>
                    <tr>
                        <td colspan="2">税金Tax (总签价*)</td>
                        <td colspan="5">{{baTable.form.items!.tax * 100}}%增值税抵扣发票</td>
                        <td>￥{{parseMOney(projectTotal.total.budget_rate, true)}}</td>
                        <td>￥{{parseMOney(projectTotal.total.calculate_rate, true)}}</td>
                        <td :key="index" v-for="item, index in 3"></td>
                    </tr>							
                    <tr bgcolor="#eee">
                        <td colspan="2">TOTAL (RMB)</td>
                        <td colspan="5">总支出（人民币含税）</td>
                        <td>￥{{parseMOney(projectTotal.total.budget_total, true)}}</td>
                        <td>￥{{parseMOney(projectTotal.total.calculate_total, true)}}</td>
                        <td>￥{{parseMOney(projectTotal.total.paid, true)}}</td>
                        <td>￥{{parseMOney(projectTotal.total.no_paid, true)}}</td>
                        <td></td>
                    </tr>
                    <!-- <tr>
                        <td colspan="13">A.请不要私自删除表格内项目栏，如果没有发生费用就空着。</td>
                    </tr>
                    <tr>
                        <td colspan="13">B.关于预支:备注栏请按照此格式写：max-0101-预交通1000元或者小储-0211-预车费1000餐2000（人名+日期+对应预支事项+金额）	</td>
                    </tr>
                    <tr>
                        <td colspan="13">C.保存格式请保存Excel档	</td>
                    </tr>
                    <tr>
                        <td colspan="13">D.如备注栏无法写入，请用加入注释的方式来表达</td>
                    </tr> -->
                    <tr>
                        <td :key="index" v-for="item, index in 12">&nbsp;</td>
                    </tr>
                    <template :key="index" v-for="(item, index) in tableData">
                        <tr class="bold">
                            <td colspan="2">{{item.title}}</td>
                            <td width="200">备注</td>
                            <td>UNIT</td>
                            <td>QTY</td>
                            <td>TERMS</td>
                            <td>RATE</td>
                            <td>预算栏</td>
                            <td>核算栏</td>
                            <td>已支付</td>
                            <td>未支付</td>
                            <td>预支</td>
                        </tr>
                        <tr :key="ii" v-for="(val, ii) in item.children">
                            <td>{{ ii+1 }}</td>
                            <td>
                                <template v-if="val.id > 10000">
                                    <el-input @blur="inputBlur" @input="inputInput" size="small" id="table-input" v-model="val.title"  v-if="tableEditKey == `${ii}-${index}-title`"></el-input>
                                    <div class="table-input-item" @click="onCellClick(val,'title', ii, index)" v-else>
                                        <el-text>{{val.title}}</el-text>
                                    </div>
                                </template>
                                <span v-else>
                                    {{val.title}}
                                </span>
                            </td>
                            <td>
                                <el-input @blur="inputBlur" @input="inputInput" size="small" id="table-input" v-model="val.remark"  v-if="tableEditKey == `${ii}-${index}-remark`"></el-input>
                                <div class="table-input-item" @click="onCellClick(val,'remark', ii, index)" v-else>
                                    <el-text>{{val.remark}}</el-text>
                                </div>
                            </td>
                            <td>{{ val.unit }}</td>
                            <td>{{ val.qty }}</td>
                            <td>{{ val.trems }}</td>
                            <td>{{ val.rate }}</td>
                            <td>{{ val.budget }}</td>
                            <td>{{ val.calculate }}</td>
                            <td>{{ parseMOney(val.paid) }}</td>
                            <td>{{ parseMOney(val.no_paid) }}</td>
                            <td>
                                {{ advance_statics[val['id']] != undefined  ? advance_statics[val['id']]['amount'] : "" }}
                            </td>
                        </tr>
                        <tr bgcolor="#eee">
                            <td>Sub Total</td>
                            <td></td>
                            <td>共计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>{{ statics[index] ? statics[index]['budget'] : '' }}</td>
                            <td>{{ statics[index] ? statics[index]['calculate'] : '' }}</td>
                            <td>{{ statics[index] ? statics[index]['paid'] : '' }}</td>
                            <td>{{ statics[index] ? statics[index]['no_paid'] : '' }}</td>
                            <td></td>
                        </tr>
                        <tr v-if="index < tableData.length - 1">
                            <td colspan="12">&nbsp;</td>
                        </tr>
                    </template>
                </table>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="onClosed">关闭</el-button>
                <el-button type="primary" :disabled="disabledSubmit" @click="onSubmit">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
interface tableData {
    id: number
    title: string
    pid: number
    unit: number
    qty: number
    trems: string
    rate: number
    budget: number
    calculate: number
    children?: tableData[]
}

interface statics {
    budget: number
    calculate: number
    id: number
    title: string
    subTotal?: string|number
    subRate?: string|number
}

interface FormData {
    id: number
    title: string
    remark: string
}

import { ElLoading, ElMessage } from 'element-plus'
import { inject, reactive, ref, onMounted, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import { getProjectFeeitem, getProjectFeeitemStatics, exportProject, updateProjectFeeitemRemark } from '/@/api/backend/index'
import { fullUrl } from '/@/utils/common'


const baTable = inject('baTable') as baTableClass
const tableHeight = ref()
const { t } = useI18n()
const letters = [ 'A','B','C','D','E','F','G','H','I','J','K','L','M','N', 'O', 'P','Q', 'R','S','T' ]
const disabledSubmit = ref(true)
onMounted(() => {
    tableHeight.value = window.innerHeight * 1 - 457;    
})

let tableData: any = ref([])
let tabModel = ref('')
let tableEditKey = ref('')
let statics = ref([])
let projectTotal = reactive({advance:0, payment:0, reimbursement:0,total: {budget: 0, calculate: 0, rate:0.06, budget_rate: 0, calculate_rate: 0, budget_total: 0, calculate_total: 0,paid:0, no_paid: 0}})
let requestTimes = 0
let formData:FormData[] = []
const advance_statics = ref([])

const onOpen = () => {
    projectTotal.total.rate = Number(baTable.form.items!.tax)
    getProjectFeeitem({project_id: baTable.form.items!.id}).then((res: any) => {
        const { list } = res.data
        list.forEach((item: any) => {
            let ele = {
                dbId: item.id,
                id: item.feeitem_id,
                title: item.feeitem_name,
                pTitle: item.feeitem_pname,
                remark: item.remark,
                pid: item.feeitem_pid,
                unit: item.unit,
                qty: item.qty,
                trems: item.trems,
                rate: item.rate,
                budget: item.budget,
                calculate: item.calculate,
                paid: item.paid > 0 ? item.paid : '',
                no_paid: item.calculate > 0 ? (item.calculate - (item.paid ? item.paid : 0)) : ''
            }
            setTableDataItem(ele)
        })
        tableData.value.sort((a: any, b: any) => {
            return b.id - a.id
        })
        tabModel.value = `table${tableData.value[0]['id']}`
        afterOpen()
    })
    getProjectFeeitemStatics({project_id: baTable.form.items!.id}).then((res: any) => {
        let total = { id:999, title: '总计', budget: 0, calculate: 0,paid: 0,no_paid:0, subTotal: 0, subRate : '' }
        let { advance, payment, reimbursement } = res.data
        res.data.statics.sort((a: any, b: any) => {
            return b.id - a.id
        })
        advance_statics.value = res.data.advance_statics
        res.data.statics.map((item: any) => {
            total.budget += Number(item.budget)
            total.calculate += Number(item.calculate)
            projectTotal.total.budget += Number(item.budget)
            projectTotal.total.calculate += Number(item.calculate)
            total.paid += isNaN(Number(item.paid)) ? 0 : Number(item.paid)
            total.no_paid = total.calculate - total.paid
            let subTotal = Number(item.budget - item.calculate)
            let subRate = item.budget == 0 ? subTotal : (Number((subTotal/item.budget).toFixed(2)) * 100) + '%'
            statics.value.push({...item, subTotal, subRate})
        })
        total.subTotal = Number(total.budget - total.calculate)
        total.subRate = total.budget == 0 ? total.subTotal : (Number((total.subTotal/total.budget).toFixed(2)) * 100) + '%'
        projectTotal.advance = advance
        projectTotal.payment = payment
        projectTotal.reimbursement = reimbursement
        projectTotal.total.budget_rate = (projectTotal.total.budget * projectTotal.total.rate).toFixed(2);
        projectTotal.total.calculate_rate = (projectTotal.total.calculate * projectTotal.total.rate).toFixed(2);
        projectTotal.total.budget_total = projectTotal.total.budget + Number(projectTotal.total.budget_rate)
        projectTotal.total.calculate_total = projectTotal.total.calculate + Number(projectTotal.total.calculate_rate)
        projectTotal.total.paid = total.paid
        projectTotal.total.no_paid = total.no_paid
        // statics.value.splice(0,0, total)
        afterOpen()
    })
}

const setTableDataItem = (ele: any) => {
    const pIndex = tableData.value.findIndex((p: any) => p.id == ele.pid)
    if(pIndex == -1){
        tableData.value.push({
            id: ele.pid,
            title: ele.pTitle,
            pid: 0,
            budget: 0,
            calculate: 0,
            children: [
                {
                    dbId: ele.dbId,
                    id: ele.id,
                    title: ele.title,
                    pid: ele.pid,
                    remark: ele.remark,
                    unit: ele.unit ? ele.unit : 0,
                    qty: ele.qty ? ele.qty : 0,
                    trems: ele.trems ? ele.trems : '',
                    rate: ele.rate ? ele.rate : 0,
                    budget: ele.budget ? ele.budget : 0,
                    calculate: ele.calculate ? ele.calculate : 0,
                    paid: ele.paid ?? "",
                    no_paid: ele.calculate > 0 ? (ele.calculate - (ele.paid ? ele.paid : 0)) : ''
                }
            ]
        })
    } else {
        const cIndex = tableData.value[pIndex]['children']?.findIndex((p: any) => p.id == ele.id)
        if(cIndex == -1){
            tableData.value[pIndex]['children']?.push({
                dbId: ele.dbId,
                id: ele.id,
                title: ele.title,
                remark: ele.remark,
                pid: ele.pid,
                unit: ele.unit ? ele.unit : 0,
                qty: ele.qty ? ele.qty : 0,
                trems: ele.trems ? ele.trems : '',
                rate: ele.rate ? ele.rate : 0,
                budget: ele.budget ? ele.budget : 0,
                calculate: ele.calculate ? ele.calculate : 0,
                paid: ele.paid ?? "",
                no_paid: ele.calculate > 0 ? (ele.calculate - (ele.paid ? ele.paid : 0)) : ''
            })
            tableData.value[pIndex]['children'].sort((a:any, b:any) => {
                if(a.id > 10000){
                    return a.id - b.id
                } else {
                    return b.id - a.id
                }
            })
        }
    }
}

const onCellClick = (row: any, field: string, index: Number, pIndex: Number) => {
    tableEditKey.value = `${index}-${pIndex}-${field}`
    nextTick(() => {
        document.getElementById('table-input')?.focus()
    })
}

const onClosed = () => {
    baTable.toggleForm()
    tableData.value = []
    statics = ref([])
    requestTimes = 0
    projectTotal = reactive({advance:0, payment:0, reimbursement:0,total: {budget: 0, calculate: 0,rate:0.06, budget_rate: 0, calculate_rate: 0, budget_total: 0, calculate_total: 0,paid:0, no_paid: 0}})
    disabledSubmit.value = true
    formData = []
    advance_statics.value = []
}

const afterOpen = () => {
    requestTimes++
    if(requestTimes == 2 && baTable.form.operate == 'export'){
        const loading = ElLoading.service({

            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        // var table_elt = document.getElementById("detail-table")
        // var workbook = XLSX.utils.table_to_book(table_elt)
        // var ws = workbook.Sheets["Sheet1"]
        // // XLSX.utils.sheet_add_aoa(ws, [["Created "+new Date().toISOString()]], {origin:-1})
        // XLSX.writeFile(workbook, "Report.xlsb");
        // 线上会报错 添加一点延时 OK
        setTimeout(() => {
            exportProject({
                detail: baTable.form.items!,
                statics: statics.value,
                tableData: tableData.value,
                advance_statics: advance_statics.value,
                projectTotal: projectTotal
            }).then((res: any) => {
                window.open(fullUrl(res.data.file))
                loading.close()
            })
        }, 50)
    }
}

const inputBlur = () => {
    tableEditKey.value = ``
}
const inputInput = (value: string) => {
    disabledSubmit.value = false
    let keys = tableEditKey.value.split('-')
    const index = keys[0]
    const pIndex = keys[1]
    const field = keys[2]

    const row = tableData.value[pIndex]['children'][index]
    const id = row.dbId

    const formDataIndex = formData.findIndex((p: any) => p.id == id)
    if(formDataIndex > 0){
        formData[formDataIndex][field] = value
    } else {
        let tempData:FormData = {
            id: id,
            title: row.title,
            remark: row.remark,
        }
        tempData[field] = value
        formData.push(tempData)
    }
}

const onSubmit = () => {
    updateProjectFeeitemRemark(formData).then((res: any) => {
        ElMessage({
            message: '保存成功',
            type: 'success',
        })
        setTimeout(() => {
            baTable.toggleForm()
        }, 1000)
    })
}

const parseMOney = (money: string|number, hasZero: Boolean = false) => {
    if(money == "") return hasZero ? '0.00' :"";
    let num = Number(money)
    return num.toFixed(2)
}
</script>
<style lang="scss">
    .el-dialog.cu-dialog.is-fullscreen { overflow: hidden; }
</style>
<style scoped lang="scss">
    .ba-operate-dialog :deep .el-dialog__body { padding-bottom: 0; height: calc(100vh - 100px); }
    .info-content {
        border-right: 1px solid #ddd; height: calc(100vh - 175px);
        .info-content-item {
            display: flex; justify-content: space-between; padding: 5px 10px; align-items: center;
            .label { display: inline-block; white-space: nowrap; padding-right: 13px;}
            .value {
                .ml-2 { 
                    margin-bottom: 10px;
                    margin-right: 10px
                }
            }
            div.value {
                
            }
        }
    }
    .table-warp { }
    .title { font-size: 14px; font-weight: bold; padding: 8px 0; }
    .table-input-item { display: flex; justify-content: space-between; align-items: center; }
    .statics-warp {
        display: flex; 
        justify-content: flex-start;
        .statics-item {
            border: 1px solid #ddd; border-radius: 5px; box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
            width: 180px;
            .title { padding: 10px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between;}
            .content { padding: 10px; display: flex; justify-content: flex-end; }
        }
        .statics-item + .statics-item { 
            margin-left: 20px;
        }

    } 

    .content-table { width: 100%; border-collapse:collapse}
    .content-table td { height: 35px; line-height: 35px; padding: 0 10px; text-align: center; border-color: #ddd;}
    .content-table td[align="left"] { text-align: left; }
    .content-table .bold { font-weight: bold; }
    .ba-table-form-scrollbar { height: calc(100vh - 130px); }
    .table-input-item { display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px dashed #eee;
    padding-left: 5px;
    height: 25px;}
</style>
